<template>
  <!-- 新增用户弹框 -->
  <el-dialog title="新增用户" :visible="userAddDialogVisible" @close="onClose">
    <el-form :model="userAddForm">
      <el-form-item label="用户名" :label-width="userAddFormLabelWidth">
        <el-input v-model="userAddForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" :label-width="userAddFormLabelWidth">
        <el-input v-model="userAddForm.password"></el-input>
      </el-form-item>
      <el-form-item label="角色" :label-width="userAddFormLabelWidth">
        <el-select v-model="roles" multiple placeholder="请选择">
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" :label-width="userAddFormLabelWidth">
        <el-input v-model="userAddForm.descr"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="handleSubmit">确认</el-button>
      <el-button type="danger" size="mini" @click="onCancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getList, addUser } from "@/api/user";
import { getRoleOptions } from "@/api/role";

export default {
  name: "UserAdd",
  props: ["userAddDialogVisible"],
  data() {
    return {
      //   listLoading: true,
      userAddForm: {
        username: "",
        password: "",
        descr: "",
      },
      userAddFormLabelWidth: "100px",
      roles: [],
      roleOptions: [],
    };
  },
  methods: {
    reset() {
      this.userAddForm.username = "";
      this.userAddForm.password = "";
      this.userAddForm.descr = "";
    },
    handleSubmit() {
      console.log(this.roles)

      var roleIds = "";
      if(this.roles.length > 0){
        roleIds = this.roles.join(",")
      }
      
      var params = {
        roleIds: roleIds,
        username: this.userAddForm.username,
        password: this.userAddForm.password,
        descr: this.userAddForm.descr,
      };

      addUser(params).then((response) => {
        if (response.data == 1) {
          this.reset();
          this.$emit("success");
        } else {
          this.reset();
          this.$emit("failed", response.data.msg);
        }
      });
    },
    onCancel() {
      this.$emit("cancel");
    },
    onClose() {
      this.$emit("close");
    },
  },
  watch: {
    userAddDialogVisible() {
      if (this.userAddDialogVisible) {
        getRoleOptions().then((response) => {
          this.roleOptions = response.data;
        });
      }
    },
  },
};
</script>
